#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021-present, sun-shine cloud, Inc.
# All rights reserved
# Author：  xiaobo
# Date：    2021-04-13
# 音频降噪任务接收程序

from flask import Flask
from flask import request, Response, make_response
from flask import abort
from urllib.parse import unquote
import logging_config
import datetime
import publicfun
import taskClass
import json

#***********************************************
#如果不需要nacos则需要把这个引入注释掉即可；
#import nacos
#import pnacos
#***********************************************

#nacos_ip = cfg.nacos_ip

#启动nacos的服务注册，注册的名称是:loopvideo-server, namespace: myspace
#NAMESPACE = "denoise"
#SERVICENAME = "denoise_web"
#pn = pnacos.pnacos(nacos_ip, NAMESPACE, SERVICENAME)
#nacos服务名和命名空间在pname中进行设置
#pn.start()
#*************************************
#如果没有设置nacos上一段的代码可以屏蔽

logger = logging_config.Config().get_config()
# _id: 任务自定义id信息(回调时候需要提供)
# ossUrl: 文件url(obs的地址)
# objectKey: 指定的存放位置(或者下发时携带用户信息和租户信息也可以, 由底层拼装objectKey)
# callbackUrl: 任务回调接口地址(回调时的地址)
# compressResultFile: true 或 false 是否压缩结果文件

app = Flask(__name__)

# @app.route("/denoise/Task", methods=["GET", "POST"])
@app.route("/denoise/newtask", methods=["POST"])
def newtask():

    try:
        start = datetime.datetime.now()
        _id = None
        ossUrl = None
        objectKey = None
        callbackUrl = None

        pjson = request.get_json()

        _id = pjson["_id"]
        ossUrl = pjson["ossUrl"]
        objectKey = pjson["objectKey"]
        callbackUrl = pjson["callbackUrl"]

        if not (_id and ossUrl and objectKey and callbackUrl):
            raise ValueError("赋值错误，请检查！")
        #把请求的内容放入到任务中去
        task = taskClass.task()
        task.addTask(_id, ossUrl, objectKey, callbackUrl)
        end = datetime.datetime.now()
        wtime = str(end - start)
        logger.info(wtime+" 秒")
        ret = publicfun.retInfo(_id, ossUrl, "请求已接收", wtime)
        
        response = Response(ret)
        response.headers['Content-Type'] = "application/json"
        return response

    except Exception as e:
        err = str(e)
        ret = publicfun.retError(_id, ossUrl, err, wtime)
        response = Response(ret)
        response.headers['Content-Type'] = "application/json"
        return response

#获取任务处理的状态
@app.route("/denoise/querytask/<taskid>", methods=["POST"])
def querytask(taskid):

    task = taskClass.task()
    res = task.queryTask(taskid)
    if not res:
        res = {"taskid":taskid, "code":-1, "info":"没有实时状态，已处理完成或者无此记录"}
    if 'ltime' in res:
        res["ltime"] = res["ltime"].strftime("%Y-%m-%d %H:%M:%S")
    if 'ctime' in res:
        res["ctime"] = res["ctime"].strftime("%Y-%m-%d %H:%M:%S")
    resStr = json.dumps(res,ensure_ascii=False)
    response = Response(resStr)
    response.headers['Content-Type'] = "application/json"
    return response

@app.route("/denoise/callback", methods=["POST"])
def taskStatus():
    pjson = request.get_json()
    print(pjson)
    return {"status": "OK"}, 200

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=False)